﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Xml.Linq;
using Commerce.Common;

namespace Commerce.Promotions
{
    public class PercentOffCouponByCategory : Coupon
    {
        public PercentOffCouponByCategory()
            : base()
        {

        }

        public PercentOffCouponByCategory(string couponCode, CouponType couponType)
            : base(couponCode, couponType)
        {
        }
        private int _percentOff;

        public int PercentOff
        {
            get { return _percentOff; }
            set { _percentOff = value; }
        }

        private List<int> _categoryForCoupon;

        [SelectorType("CategoryPicker", multiSelect = true)]
        public List<int> CategoryForCoupon
        {
            get { return _categoryForCoupon; }
            set { _categoryForCoupon = value; }
        }

        decimal CalculateDiscountAmount(decimal itemAmount)
        {

            decimal result = 0;
            decimal dPercent = Convert.ToDecimal(PercentOff);
            if (PercentOff > 0)
            {
                decimal dRate = dPercent / 100.00M;
                result = dRate * itemAmount;
                result = Math.Round(result, 2);
            }

            return result;
        }
        public override bool ApplyCouponToOrder(Commerce.Common.Order order)
        {
            //Validate the order to make sure it's good.  
            CouponValidationResponse validationResponse =
                ValidateCouponForOrder(order);
            if (!validationResponse.IsValid)
            {
                throw new ArgumentException("Coupon is not valid for order: " + validationResponse, "order");
            }

            List<int> selected = new List<int>();
            XDocument doc = XDocument.Parse(base.GetXmlData());

            if (doc.Descendants("CategoryForCoupon").Descendants("int").Count() > 0)
            {
                foreach (XElement element in doc.Descendants("CategoryForCoupon").Descendants("int"))
                {
                    selected.Add(Int32.Parse(element.Value));

                }
            }
            else
            {
                throw new ArgumentException("No categoriess selected for coupon.");
            }

            //if (!order.CouponCodes.Contains(CouponCode))
            //{
                order.DiscountAmount = 0;

                foreach (var o in order.Items)
                {
                    ProductCategoryMapCollection p = new SubSonic.Select(ProductCategoryMap.Columns.CategoryID)
                        .From(ProductCategoryMap.Schema)
                        .WhereExpression(ProductCategoryMap.Columns.CategoryID).In(selected)
                        .And(ProductCategoryMap.Columns.ProductID).IsEqualTo(o.ProductID)
                        .ExecuteAsCollection<ProductCategoryMapCollection>();

                    if (p.Count() > 0)
                    {
                        order.DiscountAmount += CalculateDiscountAmount(o.LineTotal);
                    }
                }

                //add a comment to the order
                order.CouponCodes = CouponCode;

                //save the order
                order.Save("Coupon System");
            //}

            return false;
        }
    }
}
